package com.voicechat.firstmet.activity;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.voicechat.firstmet.R;
import com.voicechat.firstmet.base.BaseActivity;
import com.voicechat.firstmet.service.FloatVideoWindowService;
import com.voicechat.firstmet.utils.PopUtils;
import com.voicechat.firstmet.utils.ScreenUtils;
import com.voicechat.firstmet.utils.StatusBarUtils;
import com.voicechat.firstmet.view.AutoVerticalScrollTextView;
import com.voicechat.firstmet.view.CircleImageView;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.activity_imessage
 * @ClassName: VoiceChatingActivity
 * @Description: 语音通话界面
 * @Author: ljp
 * @CreateDate: 2018/9/5 17:29
 * @Version: 1.0
 */
public class VoiceChatingActivity extends BaseActivity {
    @BindView(R.id.iv_close)
    ImageView ivClose;
    @BindView(R.id.tv_nike_name)
    TextView tvNikeName;
    @BindView(R.id.image_more)
    ImageView imageMore;
    @BindView(R.id.auto_gif_notice)
    AutoVerticalScrollTextView autoGifNotice;
    @BindView(R.id.linear_notice)
    LinearLayout linearNotice;
    @BindView(R.id.image_icon)
    CircleImageView imageIcon;
    @BindView(R.id.image_mic)
    ImageView imageMic;
    @BindView(R.id.image_gif)
    ImageView imageGif;
    @BindView(R.id.image_sca)
    ImageView imageSca;
    private String TAG = "VoiceChatingActivity";
    private ServiceConnection mVideoServiceConnection;
    @Override
    protected int setStatusBarColor() {
        return 0;
    }

    @Override
    protected boolean isSettingStatusBarText() {
        return false;
    }

    @Override
    protected int loadLayout() {
        return R.layout.activity_voice_chating;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        //透明状态栏
        StatusBarUtils.Full(this);
        mVideoServiceConnection = new ServiceConnection() {

            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                // 获取服务的操作对象
                FloatVideoWindowService.MyBinder binder = (FloatVideoWindowService.MyBinder) service;
                binder.getService();
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
            }
        };
    }
    /**
     * @return
     * @method
     * @description 更多popu
     * @date: 2018/9/11 19:50
     * @author: ljp
     */
    private void showPopu(View view) {
        View inflate = View.inflate(this, R.layout.popu_window_function, null);
        int viewY = (view.getBottom()*2+(view.getHeight()));
        int viewX = view.getLeft()-(int) getResources().getDimension(R.dimen.x300);
        // 设置好参数之后再show
        int local[] = new int[2];
        //弹出控件的位置，坐标存在local数组
        view.getLocationOnScreen(local);
        int width = view.getWidth();
        int height = view.getHeight();
        int x = local[0] - (ScreenUtils.getScreenWidth(context)/2) - width*2;
        int y = local[1] - height;
        // 获得位置
        int popupWidth = inflate.getMeasuredWidth();
        int popupHeight = inflate.getMeasuredHeight();
        int i = (view.getLeft() - view.getWidth()) - (local[1] - popupHeight) * 2;
        PopUtils.showPopupWindow(view, inflate, LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT,  i, viewY , true);

    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @OnClick({R.id.iv_close, R.id.image_more, R.id.image_sca, R.id.image_mic, R.id.image_gif})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_close:
                break;
            case R.id.image_more:
                showPopu(view);
                break;
            case R.id.image_sca:
                if (Settings.canDrawOverlays(this)) {
                    startVideoService();
                } else {
                    requestAlertWindowPermission();
                }
                break;
            case R.id.image_mic:
                break;
            case R.id.image_gif:
                break;
        }
    }

    @Override
    public boolean moveTaskToBack(boolean nonRoot) {
        return super.moveTaskToBack(nonRoot);
    }

    public void startVideoService() {
        moveTaskToBack(true);//最小化Activity
        Intent intent = new Intent(this, FloatVideoWindowService.class);//开启服务显示悬浮框
        bindService(intent, mVideoServiceConnection, Context.BIND_AUTO_CREATE);

    }

    private static final int REQUEST_CODE = 1;

    private void requestAlertWindowPermission() {
        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivityForResult(intent, REQUEST_CODE);
    }
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            if (Settings.canDrawOverlays(this)) {
                startVideoService();
                Log.i("onActivityResult", "onActivityResult granted");
            }
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if(isServiceRunning(this,"com.voicechat.firstmet.service.FloatVideoWindowService")){
            unbindService(mVideoServiceConnection);//不显示悬浮框
            Log.i(TAG, "onRestart: -----onRestart---");
        }
        Log.i(TAG, "onRestart: -----从悬浮窗进来后重新设置画布(判断是不是接通了---");
        /*//从悬浮窗进来后重新设置画布(判断是不是接通了)
        if (isCallEstablished) {
            //如果接通，先清除所有画布
            avChatUI.clearAllSurfaceView(avChatUI.getAccount());
            //延迟重新加载远端和本地的视频画布
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    avChatUI.initAllSurfaceView(avChatUI.getAccount());
                }
            }, 800);
        } else {
            //如果没接通，直接初始化所有画布
            avChatUI.initLargeSurfaceView(IMCache.getAccount());
        }*/
    }

    /**
     * 判断服务是否开启
     *
     * @return
     */
    public static boolean isServiceRunning(Context context, String ServiceName) {
        if (("").equals(ServiceName) || ServiceName == null)
            return false;
        ActivityManager myManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) myManager
                .getRunningServices(30);
        for (int i = 0; i < runningService.size(); i++) {
            if (runningService.get(i).service.getClassName().toString()
                    .equals(ServiceName)) {
                return true;
            }
        }
        return false;
    }
}
